package service

import (
	"errors"
	"alarmservice/com"
	"alarmservice/model"
	"strings"
	"time"
)

type TracingLastWarningTime struct {
	TracingId int64 `xorm:"pk"`
	CreateTime time.Time
}

func GetTracingLastWarningTimeByTracingIds(tracingIds []int64) (map[int64]*TracingLastWarningTime, error) {
	
	lastWarningTimes := make(map[int64]*TracingLastWarningTime)
	
	if len(tracingIds) <= 0 {
		return lastWarningTimes, nil
	}
	
	tracingIdsStr := com.SliceInt64ToSliceString(tracingIds)

	err := model.Orm.Sql("select tracing_id, max(create_time) as create_time from warning where tracing_id in (" + strings.Join(tracingIdsStr, ",") + ") group by tracing_id").Find(lastWarningTimes)
	if err != nil {
		return nil, err
	} else {
		return lastWarningTimes, nil
	}
}

func GetTracingLastWarningTime(tracingId int64) (time.Time, error) {
	if tracingId <= 0 {
		return time.Now(), errors.New("GetTracingLastWarningTime tracing id empty")
	}
	
	lastWarningTimes, err := GetTracingLastWarningTimeByTracingIds([]int64{tracingId})
	if err != nil {
		return time.Now(), err
	}
	
	if v, ok := lastWarningTimes[tracingId]; ok {
		return v.CreateTime, nil
	} else {
		//查询正确但是没有值
		return time.Now(), errors.New("empty data")
	}
}